package com.jungle.sp.daily.test.test4;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RedPacketGenerator {

    public static List<BigDecimal> divideRedPacket(BigDecimal totalAmount, int n) {
        List<BigDecimal> result = new ArrayList<>();
        Random random = new Random();
        BigDecimal remainAmount = totalAmount;

        // 剩余红包随机分配
        for (int i = 0; i < n - 1; i++) {
            BigDecimal randomAmount = getRandomAmount(remainAmount, n - result.size());
            result.add(randomAmount);
            remainAmount = remainAmount.subtract(randomAmount);
        }

        // 最后一个红包分配剩余的所有金额
        result.add(remainAmount.setScale(2, BigDecimal.ROUND_HALF_UP));

        return result;
    }

    // 生成一个随机金额，确保剩余金额可以继续分配
    private static BigDecimal getRandomAmount(BigDecimal remainAmount, int remainCount) {
        Random random = new Random();
        // 计算当前的最大可分配金额
        BigDecimal max = remainAmount.divide(BigDecimal.valueOf(remainCount), 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(2));
        BigDecimal randomAmount = BigDecimal.valueOf(random.nextDouble()).multiply(max).setScale(2, BigDecimal.ROUND_HALF_UP);
        if (randomAmount.compareTo(BigDecimal.valueOf(0.01)) < 0) {
            randomAmount = BigDecimal.valueOf(0.01);
        }
        return randomAmount;
    }

    public static void main(String[] args) {
        BigDecimal totalAmount = new BigDecimal("100");
        int n = 10; // 总红包数

        List<BigDecimal> redPackets = divideRedPacket(totalAmount, n);
        System.out.println("红包金额列表: " + redPackets);

        // 验证总金额是否正确
        BigDecimal total = redPackets.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        System.out.println("总金额: " + total);
    }
}
